package com.xc.freeapp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;

import com.xc.freeapp.bean.AuthInfo;
import com.xc.freeapp.util.AuthUtil;
import com.xc.freeapp.util.JsonUtil;

public class HttpFilter implements Filter {
	private Logger log = Logger.getLogger(this.getClass());

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterchain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		AuthInfo authInfo = JsonUtil.parseJson(
				httpServletRequest.getHeader("AuthInfo"), AuthInfo.class);
		
		log.info("AuthInfo="+authInfo);
		if (authInfo == null) {
			authInfo = new AuthInfo();
			authInfo.setAppId("1");
			authInfo.setPlatform("ios");
			authInfo.setUserId("453");
		}
		AuthUtil.setAuthInfo(httpServletRequest, authInfo);
		AuthUtil.setToken(httpServletRequest,
				httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION));
		log.info("AUTHORIZATION="+AuthUtil.getToken(httpServletRequest));
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Content-Type",
				"application/json;charset=UTF-8");
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpServletResponse.setHeader("Access-Control-Allow-Methods",
				"POST, PUT, GET, DELETE, OPTIONS"); // will need to enable other
													// methods when/as
													// implemented
		httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
		httpServletResponse
				.setHeader(
						"Access-Control-Allow-Headers",
						"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,AuthInfo");

		filterchain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
